import React, { Fragment, useCallback, useEffect, useMemo, useRef, useState } from 'react';
import NavBar from '@/components/NavBar/NavBar';
import PatientItem from '@/views/Patient/components/PatientItem/PatientItem';
import SvgIcon from '@/components/SvgIcon/SvgIcon';
import PatientPopup from '@/views/Patient/components/PatientPopup/PatientPopup';
import { Button, Popup, Toast } from 'antd-mobile';
import { useNavigate, useSearchParams } from 'react-router-dom';
import { fetchPatientList } from '@/store/modules/patientStore';
import { useEnhanceDispatch, useEnhanceSelector } from '@/hooks';
import type { Patient as PatientType } from '@/type/PatientType';
import { setPatientId } from '@/store/modules/consultStore';
import './Patient.scss';


const Patient: React.FunctionComponent = () => {
  const [searchParams, setSearchParams] = useSearchParams();
  // searchParams参数
  const selected = searchParams.get('selected') as 'Medicine' | 'Fast';
  const navigate = useNavigate();
  const enhanceDispatch = useEnhanceDispatch();
  // 就诊人列表
  const patientList = useEnhanceSelector(state => state.patientStore.patientList);
  // 是否编辑就诊人
  const [edit, setEdit] = useState<boolean>(false);
  // 是否显示和隐藏弹出层
  const [visiblePopup, setVisiblePopup] = useState<boolean>(false);
  // 子组件的ref
  const patientPopupRef = useRef<{ findPatientDetail: (patientId: string) => Promise<void> }>();
  // 左边插槽内容
  const left = useCallback(() => (<span>返回</span>), []);
  // 中间插槽内容
  const children = useCallback(() => (<span>家庭档案</span>), []);
  // 计算出来的searchParams参数
  // const selectedMemo = useMemo(() => selected === 'true' ? true : false, [selected]);
  // 默认就诊人
  const [defaultPatient, setDefaultPatient] = useState<PatientType>(() => patientList.find(item => item.defaultFlag === 1) as PatientType);

  /**
   * 获取就诊人列表的回调函数
   * */
  const fetchPatient = async () => {
    try {
      await enhanceDispatch(fetchPatientList()).unwrap();
    } catch (rejectedValueOrSerializedError: any) {
      Toast.show(rejectedValueOrSerializedError);
    }
  };

  /**
   * @description 点击添加患者的回调函数
   * */
  const handleAddPatient = () => {
    setVisiblePopup(true);
    setEdit(false);
  };

  /**
   * @description 编辑患者的回调函数(子组件调用)
   * */
  const handleEditPatient = (patientId: string) => {
    setVisiblePopup(true);
    setEdit(true);
    setTimeout(() => {
      patientPopupRef.current?.findPatientDetail(patientId);
    }, 0);
  };

  /**
   *
   *关闭弹框的回调函数(子组件调用)
   * */
  const handleCancelPopup = () => {
    setVisiblePopup(false);
  };

  /**
   * @description 添加或者编辑就诊人成功的回调函数(子组件调用)
   * */
  const handleSuccess = () => {
    setVisiblePopup(false);
    fetchPatient();
  };

  /**
   * @description 点击下一步按钮的回调函数
   * */
  const handleNext = () => {
    if (!defaultPatient)  return Toast.show('请选择患者');
    enhanceDispatch(setPatientId(defaultPatient));
    if (selected === 'Fast') {
      navigate('/consult-pay');
    } else if (selected === 'Medicine') {
      navigate('/consult-choose');
    }
  };
  /**
   * @description 渲染头部
   * */
  const renderHeader = () => {
    if (selected === 'Medicine') {
      return (
        <div className="patient-change">
          <h3>请选择用药人信息</h3>
          <p>以便医生给出更准确的治疗，信息仅医生可见</p>
        </div>
      );
    } else if (selected === 'Fast') {
      return (
        <div className="patient-change">
          <h3>请选择患者信息</h3>
          <p>以便医生给出更准确的治疗，信息仅医生可见</p>
        </div>
      );
    }
  };
  /**
   * @description 渲染底部
   * */
  const renderNextButton = () => {
    if (selected === 'Medicine' || selected === 'Fast') {
      return (
        <div className="patient-next" onClick={handleNext}>
          <Button color="primary" block>下一步</Button>
        </div>
      );
    }
  };

  useEffect(() => {
    fetchPatient();
  }, []);

  useEffect(() => {
    /*
    * 设置默认就诊人
    * */
    const defaultPatient = patientList.find(item => item.defaultFlag === 1) as PatientType;
    setDefaultPatient(defaultPatient);
  }, [patientList]);

  return (
    <Fragment>
      <div className="patient">
        {/*导航栏组件*/}
        <NavBar back={left()} children={children()} onBack={() => navigate(-1)}></NavBar>
        {/*头部信息*/}
        {renderHeader()}
        {/*患者列表*/}
        <div className="patient-list">
          {/*就诊人列表*/}
          {patientList.map((item, index) => <PatientItem setDefaultPatient={setDefaultPatient} defaultPatient={defaultPatient} patient={item} key={item.id} selected={selected} handleEdit={handleEditPatient} success={() => fetchPatient()}></PatientItem>)}
          {/*=添加就诊人*/}
          <div className="patient-add">
            <SvgIcon name="add" width="20px" height="20px"></SvgIcon>
            <p onClick={handleAddPatient}>添加患者</p>
          </div>
          <div className="patient-tip">最多可添加6人</div>
        </div>
        {/*底部按钮*/}
        {renderNextButton()}
      </div>
      {/*弹出曾*/}
      <Popup destroyOnClose visible={visiblePopup} position="right" bodyStyle={{ width: '100vw' }}>
        {/*添加或者编辑就诊人的表单*/}
        <PatientPopup onBack={handleCancelPopup} edit={edit} success={handleSuccess} ref={patientPopupRef}></PatientPopup>
      </Popup>
    </Fragment>
  );
};

export default Patient;